#!/bin/sh

# errors shouldn't cause script to exit
set +e 

# remove softlink to admin script 
rm -f /usr/sbin/rstudio-server

# remove temporary streams
rm -rf /tmp/rstudio-rsession
rm -rf /tmp/rstudio-rserver

# determine which init system is in use
# a variation on:
# https://wiki.ubuntu.com/SystemdForUpstartUsers#How_to_identify_which_init_system_you_are_currently_booting_with
INIT_SYSTEM="unknown"
if ps -p1 | grep systemd > /dev/null 2>&1; then
    # If pid 1 is systemd, this is systemd.
    INIT_SYSTEM="systemd"
elif ps -p1 | grep init > /dev/null 2>&1; then
    # If pid 1 is init and init tells us it is upstart, this is upstart.
    if /sbin/init --version | grep upstart > /dev/null 2>&1; then
        INIT_SYSTEM="upstart"
    fi
fi

# stop and remove service under systemd
if test "$INIT_SYSTEM" = "systemd"
then
   systemctl stop rstudio-server.service 2>/dev/null
   systemctl disable rstudio-server.service 2>/dev/null
   rm -rf /lib/systemd/system/rstudio-server.service
   rm -rf /usr/lib/systemd/system/rstudio-server.service
   systemctl daemon-reload
fi

# clear error termination state
set -e
